<template>
  <Dialog v-model="dialogVisible" title="导入" width="500" align-center>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      class="form-wrap"
      label-width="120px"
    >
      <el-form-item label="文件" prop="file" v-if="formType === 'create'">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :action="UPLOAD_URL"
          :headers="uploadHeaders"
          :on-error="submitFormError"
          :on-exceed="handleExceed"
          :limit="1"
          :auto-upload="false"
          style="width: 100%"
        >
          <el-button type="primary">选择文件</el-button>
          <!-- <template #tip>
            <div class="el-upload__tip"> 仅支持上传格式为text/plain的文件 </div>
          </template> -->
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import {assetMessageUploadFinger} from '@/api/assetList'
import { useUpload } from '@/views/develop/featureLibrary/useUpload.ts'
import type { UploadInstance, UploadRawFile } from 'element-plus'


export type FormType = 'create' | 'update' | ''

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中

const uploadRef = ref<UploadInstance>()

const {
  uploadHeaders,
  UPLOAD_URL,
  fileList, // 文件列表
  handleExceed,
  submitFormError
} = useUpload(uploadRef)

watch(
  fileList,
  (files) => {
    if (files.length > 0) {
      formData.value.file = files[0].raw
    } else {
      formData.value.file = undefined
    }
    formRef.value!.validateField('file')
  },
  {
    deep: true
  }
)

const formType = ref<FormType>('') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  id: undefined,
  name: '',
  file: undefined as UploadRawFile | undefined,
  deptId: '' as string | number,
  systemId: '',
  standardId: '',
  levelId: '' as string | number,
  classificationId: ''
})

const formRules = reactive({
  file: [{ required: true, message: '文件不能为空', trigger: ['blur', 'change'] }]
})
const formRef = ref<FormInstance>() // 表单 Ref

/** 打开弹窗 */

const open = async () => {
  dialogVisible.value = true
  formType.value = 'create'

}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value?.validate()

  // 提交请求
  formLoading.value = true

  const formData_ = new FormData()

  for (const [key, value] of Object.entries(toRaw(formData.value))) {
    if (value) {
      if (key === 'file') {
        formData_.append(key, value as UploadRawFile)
      } else {
        formData_.append(key, '' + value)
      }
    }
  }
  try {
    let res
    if (formType.value === 'create') {
      res = await assetMessageUploadFinger(formData_)
    }
    console.log('res',res)
    formType.value === 'create'
      ? message.success(t('common.createSuccess'))
      : message.success(t('common.updateSuccess'))
    closeDialog()
    // 发送操作成功的事件
    emit('success',res.data)
  } finally {
    formLoading.value = false
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  formLoading.value = false

  formData.value = {
    id: undefined,
    name: '',
    file: undefined,
    deptId: '',
    systemId: '',
    standardId: '',
    levelId: '',
    classificationId: ''
  }
  uploadRef.value && uploadRef.value.clearFiles()
  formRef.value?.resetFields()
  fileList.value = []
}

function closeDialog() {
  dialogVisible.value = false
}

watch(dialogVisible, (show) => {
  !show && resetForm()
})



onMounted(() => {
})
</script>
<style lang="scss" scoped></style>
